from flask import Flask, render_template, request, redirect, url_for
import os
import time

app = Flask(__name__)

def get_time():
    return time.strftime('%Y-%m-%d_%H:%M:%S')

def get_domain(url):
    return url.split('/')[2]

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/starttest', methods=['POST'])
def starttest():
    url = request.form.get('url')
    # output_path = f'templates/output/{get_time()}_{get_domain(url)}.html'

    print(url)
    cmd = f'lighthouse --perf --chrome-flags="--headless --no-sandbox" "{url}"' # -output-path={output_path}
    print(cmd)
    os.system(cmd)
    os.system('mv /root/workspace/hk_webpage_perf/*.html /root/workspace/hk_webpage_perf/templates/output')
    return redirect(url_for('output'))

@app.route('/output')
def output():
    output_list = [os.path.basename(x) for x in os.listdir('templates/output')]
    return render_template('output.html', output_list=output_list[::-1])

@app.route('/output/<name>')
def output_detail(name):
    return render_template(f'output/{name}')

app.run(host='0.0.0.0', port=8000)